/**
 * 工具类
 */
import {ar} from "../../dist/assets/runtime-core.esm-bundler-8039551f";

// 匹配page里面所有的vue文件并动态引入
const modules = import.meta.glob('/src/page/**/*.vue');

/**
 * 存储localStorage
 * @param n 变量名
 * @param value 值
 */
export const setStore = (n, value) => {
    if (!n) return;
    localStorage.setItem(n, JSON.stringify(value));
}

/**
 * 取出localStorage
 * @param n 变量名
 * @returns {string} 值
 */
export const getStore = (n) => {
    if (!n) return;
    return JSON.parse(localStorage.getItem(n));
}

/**
 * 清除指定缓存
 * @param obj 变量名数组
 */
export const clearStore = (obj) => {
    for (const e of obj) {
        try {
            localStorage.removeItem(e);
        } catch (e) {
            console.error(e);
        }
    }
}

/**
 * 清空所有缓存
 */
export const clearAllStore = () => {
    window.localStorage.clear();
}

/**
 * @description 获取assets静态资源
 * @param url
 * @returns {string}
 */
export const getAssetsFile = (url) => {
    return new URL(`../assets/${url}`, import.meta.url).pathname;
}

/**
 * 数组转为树形结构--菜单
 */
export const menuArrayToTree = (data, pid, except) => {
    const obj = {};
    for (let i = 0; i < data.length; i++) {
        if (data[i].type == except) {
            delete data[i];
            continue;
        } else {
            obj[data[i].value] = data[i]
        }
    }
    const result = []
    data.forEach(e => {
        console.log(e.type == except)
        if (!obj[e.pid]) {
            result.push(e);
            return
        }
        obj[e.pid].children = obj[e.pid].children || [];
        obj[e.pid].children.push(e)
    })
    return result;
}

// 获取所有page下所有vue文件
export function getAllModules() {
    return Object.keys(modules).map((item) => item.replace('/src/page', 'page').replace('.vue', ''))
}

/**
 * 实现深克隆对象
 * @param obj
 * @returns {any}
 */
export const deepCloneObj = (obj) => {
    return JSON.parse(JSON.stringify(obj));
}

/**
 * 数组排序
 * @param arr
 * @param type
 * @returns {*}
 */
export const sortArray = (arr, type = 'ASC', param) => {
    return arr.sort(function (a, b) {
        return type === 'ASC' ? b[param] - a[param] : a[param] - b[param];
    })
}

/**
 * 保留对象数组的指定元素
 * @param arr
 * @param field
 * @returns {*[]}
 */
export const filterObjectArray = (arr, field) => {
    const newData = [];
    arr.map(i => {
        newData.push(i[field]);
    })
    return newData;
}
